package cn.wizzer.app.web.modules.controllers.platform.bus;


import cn.wizzer.app.bus.modules.models.BusinessFileInfo;
import cn.wizzer.app.bus.modules.models.InspectionItem;
import cn.wizzer.app.bus.modules.models.InspectionItemJudge;
import cn.wizzer.app.bus.modules.models.InspectionStandard;
import cn.wizzer.app.bus.modules.models.equipment.BusEquipment;
import cn.wizzer.app.bus.modules.services.*;
import cn.wizzer.app.sys.modules.models.Sys_dict;
import cn.wizzer.app.sys.modules.models.Sys_role;
import cn.wizzer.app.sys.modules.models.Sys_unit;
import cn.wizzer.app.sys.modules.models.Sys_user;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysRoleService;
import cn.wizzer.app.sys.modules.services.SysUnitService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.base.Globals;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.DateUtil;
import cn.wizzer.app.web.commons.utils.DoExcelUtil;
import cn.wizzer.app.web.commons.utils.PageUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.app.web.modules.controllers.open.file.UploadController;
import cn.wizzer.app.web.modules.controllers.platform.bus.excelvo.InspectionItemVo;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.integration.json4excel.J4E;
import org.nutz.integration.json4excel.J4EColumn;
import org.nutz.integration.json4excel.J4EConf;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.adaptor.JsonAdaptor;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * 标准管理
 */
@IocBean
@At("/platform/bus/ins_standard/")
public class InspectionStandardController {

    private static final Log log = Logs.get();

    @Inject
    private InspectionStandardService inspectionStandardService;

    @Inject
    private InspectionItemService inspectionItemService;
    @Inject
    private InspectionItemJudgeService inspectionItemJudgeService;
    @Inject
    private SysDictService sysDictService;
    @Inject
    private BusinessFileInfoService businessFileInfoService;
    @Inject
    BusEquipmentService busEquipmentService;

    @Inject
    SysRoleService sysRoleService;
    @Inject
    private SysUnitService sysUnitService;
    @Inject
    private SysUserService sysUserService;



    /**
     * 列表页面跳转
     * （尽量不要在跳转页面时带参数，为以后可能的前后端改造减少工作量）
     */
    @At("")
    @Ok("beetl:/platform/bus/inspectionStandard/index.html")
    @RequiresPermissions("bus.ins_standard.management")
    public void index(HttpServletRequest req) {
        req.setAttribute("yplxMap", JSONObject.fromObject(sysDictService.getCodeMap("yplx")));
        req.setAttribute("judgConditionMap", JSONObject.fromObject(sysDictService.getCodeMap("judgCondition")));
        req.setAttribute("unitOptions", JSONArray.fromObject(sysUnitService.getJybmTree()));
        req.setAttribute("judgConditionOptions", JSONArray.fromObject(sysDictService.dictCodeTree("judgCondition")));
        String sysadminRoleid = sysRoleService.fetch(Cnd.where("code", "=", "sysadmin")).getId();
        List<Sys_role> roles = StringUtil.getPlatformUser().getRoles();
        String role = roles.stream().map(t->t.getId()).collect(Collectors.joining(","));
        if (role.indexOf(sysadminRoleid)!=-1) {
            req.setAttribute("isAdmin", true);
        }else{
            req.setAttribute("isAdmin", false);
        }
    }

    /**
     * 列表页面跳转
     * （尽量不要在跳转页面时带参数，为以后可能的前后端改造减少工作量）
     */
    @At("inspection")
    @Ok("beetl:/platform/bus/inspectionStandard/index2.html")
    @RequiresPermissions("bus.ins_standard.management")
    public void index2(HttpServletRequest req) {
        req.setAttribute("yplxMap", JSONObject.fromObject(sysDictService.getCodeMap("yplx")));
        req.setAttribute("judgConditionMap", JSONObject.fromObject(sysDictService.getCodeMap("judgCondition")));
        req.setAttribute("unitOptions", JSONArray.fromObject(sysUnitService.getJybmTree()));
        req.setAttribute("judgConditionOptions", JSONArray.fromObject(sysDictService.dictCodeTree("judgCondition")));
        String sysadminRoleid = sysRoleService.fetch(Cnd.where("code", "=", "sysadmin")).getId();
        List<Sys_role> roles = StringUtil.getPlatformUser().getRoles();
        String role = roles.stream().map(t->t.getId()).collect(Collectors.joining(","));
        if (role.indexOf(sysadminRoleid)!=-1) {
            req.setAttribute("isAdmin", true);
        }else{
            req.setAttribute("isAdmin", false);
        }
    }

    /**
     * 详情页面跳转
     * 以后如果改为前后端分离，此方法作废，在前端页面跳转时带上参数
     * 然后用ajax请求数据即可
     */
    @At("/view/?")
    @Ok("beetl:/platform/bus/inspectionStandard/showView.html")
    @RequiresPermissions("bus.ins_standard.management")
    public void view(String standardId, HttpServletRequest req) {
        req.setAttribute("standardId", standardId);
        req.setAttribute("yplxMap", JSONObject.fromObject(sysDictService.getCodeMap("yplx")));
        req.setAttribute("judgConditionMap", JSONObject.fromObject(sysDictService.getCodeMap("judgCondition")));
        InspectionStandard inspectionStandard = inspectionStandardService.fetchLinks(inspectionStandardService.fetch(standardId), "inspectionItems",Cnd.NEW().asc("inspectionItemOrder"));
        for(InspectionItem item : inspectionStandard.getInspectionItems()){
            item.setItemJudges(inspectionItemJudgeService.query(Cnd.NEW().where("itemId","=",item.getId())));
        }
        req.setAttribute("object", JSONObject.fromObject(inspectionStandard));
    }


    /**
     * 检验标准
     *
     * @param pageNumber             开始页数
     * @param pageSize               分页大小
     * @param pageOrderName          排序字段名称
     * @param pageOrderBy            排序方式
     * @param productTypeCode        产品类型编码
     * @param productName            产品名称
     * @param inspectionStandardName 检验标准
     * @return
     */
    @At
    @Ok("json:full")
    @RequiresPermissions("bus.ins_standard.management.list")
    public Object data(
            @Param("pageNumber") int pageNumber,
            @Param("pageSize") int pageSize,
            @Param("pageOrderName") String pageOrderName,
            @Param("pageOrderBy") String pageOrderBy,
            @Param("productTypeCode") String productTypeCode,
            @Param("productName") String productName,
            @Param("inspectionStandard") String inspectionStandardName

    ) {
        try {
            String sql = "select * from bus_ins_standard where delFlag = 0 ";
            if(StringUtils.isNotBlank(productTypeCode)){
                sql+=" and productTypeCode like '"+productTypeCode+"%' ";
            }
            if(StringUtils.isNotBlank(productName)){
                sql+=" and productName like '%"+productName+"%' ";
            }
            if(StringUtils.isNotBlank(inspectionStandardName)){
                sql+=" and inspectionStandard like '%"+inspectionStandardName+"%' ";
            }
            sql+=StringUtil.dataScopeFilter("");
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                if ("ascending".equalsIgnoreCase(pageOrderBy)) {
                    sql+= " order by "+pageOrderName+" asc,opAt desc ";
                } else {
                    sql+= " order by "+pageOrderName+" desc,opAt desc ";
                }
            }else{
                sql+= " order by opAt desc ";
            }

            return Result.success().addData(inspectionStandardService.listPage(pageNumber, pageSize, Sqls.create(sql)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At
    @Ok("json:full")
    @RequiresPermissions("bus.ins_standard.management.list")
    public Object itemData(@Param("pageNumber") int pageNumber,@Param("pageSize") int pageSize,@Param("pageOrderName") String pageOrderName,@Param("pageOrderBy") String pageOrderBy,
            @Param("inspectionItemName") String inspectionItemName,
            @Param("insStandardId") String insStandardId) {
        try {
            Cnd cnd = Cnd.NEW().and("delFlag","=",false);
            if(StringUtils.isNotBlank(inspectionItemName)){
                cnd.and("inspectionItemName","like","'%"+inspectionItemName+"%'");
            }
            if(StringUtils.isNotBlank(insStandardId)){
                cnd.and("insStandardId","=",insStandardId);
            }
            cnd.and(StringUtil.dataScopeFilter());
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                cnd.orderBy(pageOrderName,PageUtil.getOrder(pageOrderBy));
            }else{
                cnd.desc("opAt");
            }

            return Result.success().addData(inspectionItemService.listPageLinks(pageNumber, pageSize, cnd,"itemJudges"));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }


    @Aop(TransAop.READ_COMMITTED)
    @AdaptBy(type = JsonAdaptor.class)
    @At()
    @Ok("json")
    @RequiresPermissions("bus.ins_standard.management.add")
    @SLog(tag = "新建标准", msg = "标准名称:${args[0].productTypeName}")
    public Object addDo(@Param("standard") InspectionStandard inspectionStandard) {
        try {
            inspectionStandard.setOperatorName(StringUtil.getPlatformUsername());
            inspectionStandard.setDisabled(false);
            this.inspectionStandardService.insertWith(inspectionStandard, "inspectionItems");
            for(InspectionItem item : inspectionStandard.getInspectionItems()){
                if(item.getItemJudges()!=null) {
                    for (InspectionItemJudge judge : item.getItemJudges()) {
                        inspectionItemJudgeService.vDelete(Cnd.NEW().where("itemId", "=", item.getId()));
                        judge.setItemId(item.getId());
                        inspectionItemJudgeService.insert(judge);
                    }
                }
            }
            this.inspectionStandardService.clearCache();
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @Aop(TransAop.READ_COMMITTED)
    @At()
    @Ok("json")
    @RequiresAuthentication
    @SLog(tag = "上传模板", msg = "fileId:${args[0]}")
    public Object upExcel(@Param("fileId") String fileId) {
        try {
            businessFileInfoService.execute(Sqls.create(" update bus_file_info set delFlag=1 where infoType='inspectionStandard' "));
            BusinessFileInfo reportheaderTemplate = businessFileInfoService.fetch(fileId);
            reportheaderTemplate.setInfoType("inspectionStandard");
            reportheaderTemplate.setDelFlag(false);
            businessFileInfoService.update(reportheaderTemplate);
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At()
    @Ok("json")
    @RequiresAuthentication
    public Object downExcel(HttpServletRequest req) {
        try {
            BusinessFileInfo businessFileInfo = businessFileInfoService.fetch(Cnd.NEW().where("infoType", "=","inspectionStandard").and("delFlag", "=", false));
            return Result.success(businessFileInfo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At("/edit/?")
    @Ok("json")
    @GET
    @RequiresPermissions("bus.ins_standard.management.edit")
    public Object edit(String id) {
        try {
            InspectionStandard inspectionStandard = inspectionStandardService.fetchLinks(
                    inspectionStandardService.fetch(id), "inspectionItems",Cnd.NEW().asc("inspectionItemOrder"));
            for(InspectionItem item : inspectionStandard.getInspectionItems()){
                item.setItemJudges(inspectionItemJudgeService.query(Cnd.NEW().where("itemId","=",item.getId())));
            }
            return Result.success().addData(inspectionStandard);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }

    }


    @Aop(TransAop.READ_COMMITTED)
    @AdaptBy(type = JsonAdaptor.class)
    @At
    @Ok("json")
    @RequiresPermissions("bus.ins_standard.management.edit")
    @SLog(tag = "修改标准", msg = "产品名称:${args[0].inspectionStandard}")
    public Object editDo(@Param("standard") InspectionStandard inspectionStandard) {
        try {
            inspectionStandard.setOpBy(StringUtil.getPlatformUid());
            inspectionStandard.setOperatorName(StringUtil.getPlatformUsername());
            inspectionStandard.setOpAt(Times.getTS());
            InspectionStandard standard = this.inspectionStandardService.insertOrUpdate(inspectionStandard);
            List<InspectionItem> inspectionItems = inspectionStandard.getInspectionItems();
            if(inspectionItems != null && inspectionItems.size()>0) {
                for (InspectionItem item : inspectionItems) {
                    item.setOpBy(StringUtil.getPlatformUid());
                    item.setOpAt(Times.getTS());
                    item.setInsStandardId(standard.getId());
                    this.inspectionItemService.insertOrUpdate(item);
                    this.inspectionItemService.deleteCache(item.getId());
                    inspectionItemJudgeService.execute(Sqls.create("delete from bus_ins_item_judge where itemId ='" + item.getId() + "'"));
                    if (item.getItemJudges() != null) {
                        for (InspectionItemJudge judge : item.getItemJudges()) {
                            judge.setItemId(item.getId());
                            inspectionItemJudgeService.insert(judge);
                        }
                    }
                }
            }
            this.inspectionStandardService.deleteCache(inspectionStandard.getId());
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }
    /**
     * 详情页面跳转
     * 以后如果改为前后端分离，此方法作废，在前端页面跳转时带上参数
     * 然后用ajax请求数据即可
     */
    @At("/getItem/?")
    @Ok("json")
    @RequiresPermissions("bus.ins_standard.management.edit")
    @SLog(tag = "获取项目", msg = "项目名称:${args[0].inspectionStandard}")
    public Object getItem(String id, HttpServletRequest req) {
        InspectionItem item = inspectionItemService.fetch(id);
        item.setItemJudges(inspectionItemJudgeService.query(Cnd.NEW().where("itemId","=",id)));
        return Result.success().addData(item);
    }

    @Aop(TransAop.READ_COMMITTED)
    @AdaptBy(type = JsonAdaptor.class)
    @At
    @Ok("json")
    @RequiresPermissions("bus.ins_standard.management.edit")
    @SLog(tag = "编辑项目", msg = "项目名称:${args[0].inspectionItemName}")
    public Object itemSubmit(@Param("item") InspectionItem item) {
        try {
            item.setOpBy(StringUtil.getPlatformUid());
            item.setOpAt(Times.getTS());
            this.inspectionItemService.insertOrUpdate(item);
            inspectionItemJudgeService.execute(Sqls.create("delete from bus_ins_item_judge where itemId ='" + item.getId() + "'"));
            if (item.getItemJudges() != null) {
                for (InspectionItemJudge judge : item.getItemJudges()) {
                    judge.setItemId(item.getId());
                    inspectionItemJudgeService.insert(judge);
                }
            }
            this.inspectionItemService.deleteCache(item.getId());
            this.inspectionStandardService.deleteCache(item.getInsStandardId());
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At("/enable/?")
    @Ok("json")
    @RequiresPermissions("bus.ins_standard.management.edit")
    @SLog(tag = "启用标准", msg = "标准ID:${args[1].getAttribute('standardId')}")
    public Object enable(String standardId, HttpServletRequest req) {
        try {
            req.setAttribute("standardId", standardId);
            this.inspectionStandardService.update(Chain.make("disabled", false), Cnd.where("id", "=", standardId));
            this.inspectionStandardService.deleteCache(standardId);
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At("/disable/?")
    @Ok("json")
    @RequiresPermissions("bus.ins_standard.management.edit")
    @SLog(tag = "禁用标准", msg = "标准:${args[1].getAttribute('templateId')}")
    public Object disable(String standardId, HttpServletRequest req) {
        try {
            req.setAttribute("standardId", standardId);
            this.inspectionStandardService.update(Chain.make("disabled", true), Cnd.where("id", "=", standardId));
            this.inspectionStandardService.deleteCache(standardId);
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At("/delete/?")
    @Ok("json")
    @RequiresPermissions("bus.ins_standard.management.delete")
    @SLog(tag = "删除标准", msg = "标准ID:${args[1].getAttribute('templateId')}")
    public Object delete(String standardId, HttpServletRequest req) {
        try {
            //逻辑删除
            req.setAttribute("standardId", standardId);
            List<InspectionItem> items = inspectionItemService.query(Cnd.where("insStandardId", "=", standardId));
            for (InspectionItem item : items) {
                inspectionItemService.vDelete(item.getId());
            }
            inspectionStandardService.vDelete(standardId);
            inspectionItemService.clearCache();
            inspectionStandardService.clearCache();
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @Aop(TransAop.READ_COMMITTED)
    @At("/batch/delete")
    @Ok("json")
    @RequiresPermissions("bus.ins_standard.management.delete")
    @SLog(tag = "批量删除标准", msg = "IDS:${args[1].getAttribute('ids')}")
    public Object batchDelete(@Param("ids") String[] ids, HttpServletRequest req) {
        try {
            req.setAttribute("ids", ids.toString());
            List<InspectionItem> items = inspectionItemService.query(Cnd.where("insStandardId", "in", ids));
            for (InspectionItem item : items) {
                inspectionItemService.vDelete(item.getId());
            }
            inspectionStandardService.vDelete(ids);
            inspectionItemService.clearCache();
            inspectionStandardService.clearCache();
            return Result.success("删除成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @Aop(TransAop.READ_COMMITTED)
    @At({"/itemDelete","/itemDelete/?"})
    @Ok("json")
    @RequiresPermissions("bus.ins_standard.management.delete")
    @SLog(tag = "删除项目", msg = "IDS:${args[0]}")
    public Object itemDelete(String id,@Param("ids") String[] ids, HttpServletRequest req) {
        try {
            if(ids!=null&&ids.length>0){
                inspectionItemService.delete(ids);
            }else{
                inspectionItemService.delete(id);
            }
            inspectionItemService.clearCache();
            return Result.success("删除成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At("/getItemJudgeByItemId")
    @Ok("json")
    @SLog(tag = "获取项目限值", msg = "IDS:${args[0]}")
    public Result getItemJudgeByItemId(@Param("id") String id, HttpServletRequest req) {
        try {
            List<InspectionItemJudge> list =  inspectionItemJudgeService.query(Cnd.NEW().where("itemId","=",id));
            return Result.success().addData(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @Aop(TransAop.READ_COMMITTED)
    @At("/importExcel/?")
    @Ok("json")
    @RequiresPermissions("bus.ins_standard.management.add")
    @SLog(tag = "批量导入标准", msg = "文件:${args[0]}")
    public Object importExcel(String fileId) {
        String msg = "";
        try {
            BusinessFileInfo reportheaderTemplate = businessFileInfoService.fetch(fileId);
            String uploadPath = this.getUploadPathConfig();
            String filePath = uploadPath+reportheaderTemplate.getFilePath();
            int headNum = 4;
            ArrayList<ArrayList<Object>> list = DoExcelUtil.readExcel(filePath,0,headNum,15);
            List<InspectionStandard> objEdit = new ArrayList<>();
            List<InspectionStandard> objlist = inspectionStandardService.listEntity(Sqls.create(" select * from  bus_ins_standard where delFlag=0 and disabled=0 "));
            List<BusEquipment> equipments = busEquipmentService.listEntity(Sqls.create(" select * from  bus_equipment where delFlag=0 "));

            String yplxSql =" SELECT * FROM sys_dict sd WHERE path like CONCAT((select path from sys_dict where code='yplx'),'____') ";
            List<Sys_dict> yplxDict = sysDictService.listEntity(Sqls.create(yplxSql));
            NutMap yplxMap1 = new NutMap();
            for (Sys_dict dict : yplxDict){
                yplxMap1.addv(dict.getName(),dict.getCode());
                String yplxMapxsql =" SELECT sd.code, sd. NAME FROM sys_dict sd WHERE parentId ='"+dict.getId()+"' ";
                Map<String, String> yplxMapx = sysDictService.getMap(Sqls.create(yplxMapxsql));
                NutMap yplxMap2 = new NutMap();
                for (Map.Entry<String, String> entry2 : yplxMapx.entrySet()){
                    yplxMap2.addv(entry2.getValue(),entry2.getKey());
                }
                yplxMap1.addv("children"+dict.getCode(),yplxMap2);
            }
            /*String yplxMapxsql =" SELECT sd.code, sd. NAME FROM sys_dict sd WHERE path like CONCAT((select path from sys_dict where code='yplx'),'________') ";
            Map<String, String> yplxMapx = inspectionStandardService.getMap(Sqls.create(yplxMapxsql));
            NutMap yplxMap2 = new NutMap();
            for (Map.Entry<String, String> entry : yplxMapx.entrySet()){
                yplxMap2.addv(entry.getValue(),entry.getKey());
            }*/
            Map<String, String> chargeStandardMap0 = sysDictService.getCodeMap("charge_standard");
            NutMap chargeStandardMap = new NutMap();
            for (Map.Entry<String, String> entry : chargeStandardMap0.entrySet()){
                chargeStandardMap.addv(entry.getValue(),entry.getKey());
            }
            for (int i = 0 ;i<list.size();i++) {
                ArrayList<Object> row = list.get(i);
                String rowString = row.stream().map(str -> str.toString()).collect(Collectors.joining(""));
                if(StringUtils.isNotBlank(rowString)){
                    InspectionStandard standard = new InspectionStandard();
                    if(row.size()>0&&row.get(0)!=null&&StringUtils.isNotBlank(row.get(0).toString())){
                        standard.setProductName(row.get(0).toString());
                    }else{
                        msg+="第"+(i+1+headNum)+"行【产品名称】不能为空！";
                    }
                    if(row.size()>2&&row.get(1)!=null&&row.get(2)!=null&&StringUtils.isNotBlank(row.get(1).toString())&&StringUtils.isNotBlank(row.get(2).toString())){
                        String yplx1 = row.get(1).toString();
                        String yplxId1="";
                        String yplxId2="";
                        if(Objects.isNull(yplxMap1.get(yplx1))){
                            msg+="第"+(i+1+headNum)+"行【产品类型】父类不存在，请保持与系统中一致！";
                        }else{
                            yplxId1 = yplxMap1.get(yplx1).toString();
                            //子类
                            String yplx2 = row.get(2).toString();
                            if(Objects.isNull(yplxMap1.get("children"+yplxId1))){
                                msg+="第"+(i+1+headNum)+"行【产品类型】子类“"+yplx2+"”于【产品类型】父类“"+yplx1+"”中不存在，请保持与系统中一致！";
                            }else{
                                NutMap yplxMap2 = (NutMap) yplxMap1.get("children"+yplxId1);
                                if(Objects.isNull(yplxMap2.get(yplx2))){
                                    msg+="第"+(i+1+headNum)+"行【产品类型】子类“"+yplx2+"”于【产品类型】父类“"+yplx1+"”中不存在，请保持与系统中一致！";
                                }else{
                                    yplxId2 = yplxMap2.getString(yplx2);
                                }
                            }
                            if(StringUtils.isNotBlank(yplxId1)&&StringUtils.isNotBlank(yplxId2)){
                                standard.setProductTypeCode(yplxId1+","+yplxId2);
                            }
                        }
                    }else{
                        msg+="第"+(i+1+headNum)+"行【产品类型】不能为空！";
                    }
                    if(row.size()>3&&row.get(3)!=null&&StringUtils.isNotBlank(row.get(3).toString())){
                        standard.setInspectionStandard(row.get(3).toString());
                    }else{
                        msg+="第"+(i+1+headNum)+"行【检验依据标准】不能为空！";
                    }

                    AtomicBoolean x = new AtomicBoolean(true);

                    objEdit.stream().map(t->{
                        if(t.getInspectionStandard().equals(standard.getInspectionStandard())&&t.getProductTypeCode().
                                equals(standard.getProductTypeCode())&&t.getProductName().equals(standard.getProductName())){
                            x.set(false);
                        }
                        return t;
                    }).collect(Collectors.toList());
                    if(x.get()){
                        objlist.stream().map(t->{
                            if(t.getInspectionStandard().equals(standard.getInspectionStandard())&&t.getProductTypeCode().
                                    equals(standard.getProductTypeCode())&&t.getProductName().equals(standard.getProductName())){
                                objEdit.add(t);
                                x.set(false);
                            }
                            return t;
                        }).collect(Collectors.toList());
                    }
                    if(x.get()){
                        objEdit.add(standard);
                    }
                    InspectionItem item = new InspectionItem();
                    if(row.size()>4&&row.get(4)!=null&&StringUtils.isNotBlank(row.get(4).toString())){
                        item.setInspectionItemName(row.get(4).toString());
                    }else{
                        msg+="第"+(i+1+headNum)+"行【检验项目】不能为空！";
                    }
                    if(row.size()>5&&row.get(5)!=null&&StringUtils.isNotBlank(row.get(5).toString())){
                        item.setStandardTermsNumber(row.get(5).toString());
                    }
                    if(row.size()>6&&row.get(6)!=null&&StringUtils.isNotBlank(row.get(6).toString())){
                        item.setSpecification(row.get(6).toString());
                    }
                    if(row.size()>7&&row.get(7)!=null&&StringUtils.isNotBlank(row.get(7).toString())){
                        item.setSampleCount(Integer.valueOf(row.get(7).toString()));
                    }
                    if(row.size()>8&&row.get(8)!=null&&StringUtils.isNotBlank(row.get(8).toString())){
                        item.setInspectionPrice(Float.valueOf(row.get(8).toString()));
                    }else{
                        item.setInspectionPrice(0f);
                    }
                    if(row.size()>9&&row.get(9)!=null&&StringUtils.isNotBlank(row.get(9).toString())){
                        item.setChargeStandardName(row.get(9).toString());
                        if(chargeStandardMap.get(row.get(9).toString())!=null){
                            item.setChargeStandardCode(chargeStandardMap.get(row.get(9).toString()).toString());
                        }else{
                            msg+="第"+(i+1+headNum)+"行【收费标准】不存在，请保持与系统中一致！";
                        }
                    }
                    if(row.size()>10&&row.get(10)!=null&&StringUtils.isNotBlank(row.get(10).toString())){
                        item.setCountUnit(row.get(10).toString());
                    }
                    if(row.size()>11&&row.get(11)!=null&&StringUtils.isNotBlank(row.get(11).toString())){
                        item.setInspectionCycle(row.get(11).toString());
                    }else {
                        msg+="第"+(i+1+headNum)+"行【检验周期】不能为空！";
                    }
                    if(row.size()>12&&row.get(12)!=null&&StringUtils.isNotBlank(row.get(12).toString())){
                        item.setInspectorUnitName(row.get(12).toString());
                        Sys_unit unit= sysUnitService.fetch(Cnd.NEW().and("name","=",item.getInspectorUnitName()).and("delFlag","=",false));
                        if(unit!=null){
                            item.setInspectorUnitId(unit.getId());
                        }else{
                            msg+="第"+(i+1+headNum)+"行【默认检验部门/组】不存在，请保持与系统中一致！";
                        }
                    }
                    if(row.size()>13&&row.get(13)!=null&&StringUtils.isNotBlank(row.get(13).toString())){
                        item.setInspectorUserName(row.get(13).toString());
                        String[] usernames = item.getInspectorUserName().split("、");
                        List<String> userIds = new ArrayList<>();
                        for(String username :usernames){
                            Sys_user user = sysUserService.fetch(Cnd.NEW().and("delFlag","=",false).and("disabled","=",false)
                                    .and("unitid","=",item.getInspectorUnitId()).and("username","=",username));
                            if(user!=null){
                                userIds.add(user.getId());
                            }else{
                                msg+="第"+(i+1+headNum)+"行【默认检验人员】："+username+"不存在，或不在表中部门下，请保持与系统中一致！";
                            }
                        }
                        //Sys_unit unit= sysUnitService.fetch(Cnd.NEW().and("name","=",item.getInspectorUnitName()).and("delFlag","=",false));
                        if(userIds.size()>0){
                            String userId = userIds.stream().collect(Collectors.joining(","));
                            item.setInspectorUserId(userId);
                        }else{
                            msg+="第"+(i+1+headNum)+"行【默认检验人员】不存在，或不在表中部门下，请保持与系统中一致！";
                        }
                    }
                    if(row.size()>14&&row.get(14)!=null&&StringUtils.isNotBlank(row.get(14).toString())){
                        item.setInspectorMethod(row.get(14).toString());
                    }
                    if(row.size()>15&&row.get(15)!=null&&StringUtils.isNotBlank(row.get(15).toString())){
                        item.setEnvironmentStandard(row.get(15).toString());
                    }
                    if(row.size()>16&&row.get(16)!=null&&StringUtils.isNotBlank(row.get(16).toString())){
                        String[] eCode = row.get(16).toString().split(",");
                        item.setEquipmentCode(row.get(16).toString());
                        for(int e = 0;e<eCode.length;e++){
                            AtomicBoolean b = new AtomicBoolean(true);
                            int finalE = e;
                            equipments.stream().map(t->{
                                if(t.getCode().equals(eCode[finalE])){
                                    /*item.setEquipmentId(t.getId());
                                    item.setEquipmentName(t.getName());*/
                                    b.set(false);
                                }
                                return t;
                            }).collect(Collectors.toList());
                            if(b.get()){
                                msg+="第"+(i+1+headNum)+"行【设备编号："+eCode[e]+"】不存在，请保持与系统中一致！";
                            }
                        }
                    }
                    if(row.size()>17&&row.get(17)!=null&&StringUtils.isNotBlank(row.get(17).toString())){
                        item.setRemark(row.get(17).toString());
                    }
                    objEdit.stream().map(t->{
                        if(t.getInspectionStandard().equals(standard.getInspectionStandard())&&t.getProductTypeCode().
                                equals(standard.getProductTypeCode())&&t.getProductName().equals(standard.getProductName())){
                                if(t.getInspectionItems()==null){
                                    t.setInspectionItems(new ArrayList<InspectionItem>());
                                }
                                t.getInspectionItems().add(item);
                        }
                        return t;
                    }).collect(Collectors.toList());
                }
            }

            if(msg.equals("")){
                for (InspectionStandard standard : objEdit){
                    standard.setOpBy(StringUtil.getPlatformUid());
                    standard.setOperatorName(StringUtil.getPlatformUsername());
                    standard.setOpAt(Times.getTS());
                    inspectionStandardService.insertOrUpdate(standard);
                    for(InspectionItem item : standard.getInspectionItems()){
                        item.setOpBy(StringUtil.getPlatformUid());
                        item.setOpAt(Times.getTS());
                        item.setInsStandardId(standard.getId());
                        inspectionItemService.insertOrUpdate(item);
                    }
                }
                return Result.success("导入成功！");
            }else{
                return Result.error(msg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return Result.error(msg);
    }


    private String getUploadPathConfig() throws Exception {
        String uploadPath;
        //系统没开启配置,上传到项目路径
        if ("false".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false"))){
            uploadPath= UploadController.class.getClassLoader().getResource("").getPath()+"upload";
        }else if (
                ("true".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false")))&&(Globals.MyConfig.getOrDefault("ConfigUploadPath", null)!=null)
        ){
            uploadPath=Globals.MyConfig.get("ConfigUploadPath").toString();
        }else {
            throw new Exception("文件上传路径配置有误");
        }
        return uploadPath;
    }


    @At
    @Ok("void")
    @RequiresAuthentication
    public void exportExcel(@Param("productTypeCode") String productTypeCode,
                       @Param("productName") String productName,
                       @Param("inspectionStandard") String inspectionStandardName,
                       @Param("pageOrderName") String pageOrderName,
                       @Param("pageOrderBy") String pageOrderBy,
                       HttpServletResponse response) {
        try {
            Cnd cnd = Cnd.NEW().and("delFlag","=",false);
            if(StringUtils.isNotBlank(productTypeCode)){
                cnd.and("productTypeCode","=",productTypeCode+"%' ");
            }
            if(StringUtils.isNotBlank(productName)){
                cnd.and("productName","=","%"+productName+"%");
            }
            if(StringUtils.isNotBlank(inspectionStandardName)){
                cnd.and("inspectionStandard","=","%"+inspectionStandardName+"%");
            }

            cnd.and(StringUtil.dataScopeFilter());
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                if ("ascending".equalsIgnoreCase(pageOrderBy)) {
                    cnd.asc(pageOrderName);
                } else {
                    cnd.desc(pageOrderName);
                }
            }
            cnd.desc("opAt");
            List<InspectionStandard> listObj = inspectionStandardService.query(cnd);
            Map yplxMap = sysDictService.getCodeMap("yplx");
            Map judgConditionMap  = sysDictService.getCodeMap("judgCondition");
            Map chargeStandardMap = sysDictService.getCodeMap("charge_standard");
            List<InspectionItemVo> vos = new ArrayList<>();
            for(InspectionStandard standard : listObj){
                List<InspectionItem> items = inspectionItemService.query(Cnd.NEW().and("insStandardId","=",standard.getId()).and("delFlag","=",false).asc("inspectionItemOrder"));
                for(InspectionItem item : items){
                    InspectionItemVo vo = new InspectionItemVo();
                    //产品名称
                    vo.setProductName(standard.getProductName());

                    String[] yplx = standard.getProductTypeCode().split(",");
                    //父类
                    vo.setProductTypeName1(StringUtil.getDict(yplx[0],yplxMap));
                    //子类
                    vo.setProductTypeName2(StringUtil.getDict(yplx[1],yplxMap));
                    //检验依据标准
                    vo.setInspectionStandard(standard.getInspectionStandard());
                    //检验项目
                    vo.setInspectionItemName(item.getInspectionItemName());
                    //条款号
                    vo.setStandardTermsNumber(item.getStandardTermsNumber());
                    //规格型号
                    vo.setSpecification(item.getSpecification());
                    //样品数量
                    vo.setSampleCount(item.getSampleCount());
                    //检验费用
                    vo.setInspectionPrice(item.getInspectionPrice());
                    //收费标准
                    if(StringUtils.isNotEmpty(item.getChargeStandardName()))
                        vo.setChargeStandardName(StringUtil.getDict(item.getChargeStandardCode(),chargeStandardMap));
                    //计量单位
                    vo.setCountUnit(item.getCountUnit());
                    //检验周期（天）
                    vo.setInspectionCycle(item.getInspectionCycle());
                    //默认检验部门
                    vo.setInspectorUnitName(item.getInspectorUnitName());
                    //默认检验人员
                    vo.setInspectorUserName(item.getInspectorUserName());
                    //检验方法
                    vo.setInspectorMethod(item.getInspectorMethod());
                    //环境要求
                    vo.setEnvironmentStandard(item.getEnvironmentStandard());
                    //设备编号
                    vo.setEquipmentCode(item.getEquipmentCode());
                    //备注
                    vo.setRemark(item.getRemark());
                    //标准限值
                    List<InspectionItemJudge> judges = inspectionItemJudgeService.query(Cnd.NEW().where("itemId","=",item.getId()));
                    if(judges.size()>0){
                        String jud = judges.stream().map(t -> StringUtil.getDict(t.getJudgeCondition(),judgConditionMap)+t.getJudgeValue()).collect(Collectors.joining(";"));
                        vo.setItemJudges(jud);
                    }
                    vos.add(vo);
                }
            }

            J4EConf j4eConf = J4EConf.from(InspectionItemVo.class);
            List<J4EColumn> jcols = j4eConf.getColumns();
            for (J4EColumn j4eColumn : jcols) {
                if ("opBy".equals(j4eColumn.getFieldName()) || "opAt".equals(j4eColumn.getFieldName()) || "delFlag".equals(j4eColumn.getFieldName())) {
                    j4eColumn.setIgnore(true);
                }
            }
            j4eConf.setSheetName(j4eConf.getSheetName()+ DateUtil.getDate());
            OutputStream out = response.getOutputStream();
            response.setHeader("content-type", "application/shlnd.ms-excel;charset=utf-8");
            response.setHeader("content-disposition", "attachment; filename=" + new String(j4eConf.getSheetName().getBytes(), "ISO-8859-1") + ".xls");
            J4E.toExcel(out, vos, j4eConf);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
